package com.etc.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class AuthFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		System.out.println("-------filter init-------");
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		System.out.println("==========doFilter==aaa=======");
		
		HttpServletRequest req = (HttpServletRequest) request;
		
		// login.action  login.jsp  js/**.js  js/**.css randomimg.action
		// login.action|login.jsp|.js$|....
		String url = req.getServletPath();
		if (url.endsWith(".js") 
				||url.endsWith(".css")
				||url.endsWith(".img")
				||url.endsWith("login.jsp")
				||url.endsWith("login.action")
				||url.endsWith("randomimg.action")) {
			// 某个方法，执行就链继续走
			chain.doFilter(request, response);
		
		} else if (req.getSession().getAttribute("uname") != null) {
			// session 有用户名这个数据--> 登录过吧
			
			// 某个方法，执行就链继续走
			chain.doFilter(request, response);
		
		} else {
			
			req.setAttribute("msg", "请先登录系统");
			req.getRequestDispatcher("login.jsp").forward(request, response);
			
		}
		System.out.println("==========doFilter==bbb=======");
	}

	@Override
	public void destroy() {
		System.out.println("==========destroy=========");
	}

}
